<!-- 弹窗 -->
<template>
  <a-modal
    :title="currentShowConfig.title"
    :visible="visible"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
    :closable="false"
    :keyboard="false"
    width="40%"
    cancelText="关闭"
    okText="导出"
  >
    <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <template v-for="keyName in formList">
        <a-form-model-item :key="keyName" :label="currentShowConfig.label" :prop="currentShowConfig.keyName">
          <component
            :open="yearShowOne"
            @openChange="openChangeOne"
            @panelChange="handlePanelChange"
            :is="currentShowConfig.type"
            v-model="form[keyName]"
            v-bind="currentShowConfig.attrs"
          ></component>
        </a-form-model-item>
      </template>
    </a-form-model>
  </a-modal>
</template>

<script>
import { outputEexportBase } from '@/api/project/productionRecords'
import { handleExcel } from './components/Excel'
import { projectApiUrlList } from '@/api/config.js'
import moment from 'moment'
import Vue from 'vue'
export default {
  name: 'BaseDialog',
  props: ['dialogVisibleType'],
  data() {
    return {
      labelCol: { span: 10 },
      projectApiUrlList,
      wrapperCol: { span: 4 },
      visible: false,
      confirmLoading: false,
      form: {},
      rules: {},
      yearShowOne: false,
      dialogConifig: {
        // 导出基础产值数据
        exportBaseVal: {
          title: '导出基础产值数据',
          label: '请选择需要导出数据的月份',
          keyName: 'month',
          type: 'a-month-picker',
          rules: {
            month: [{ required: true, message: '请选择', trigger: 'change' }]
          }
        },
        exportCompanyVal: {
          title: '导出公司汇总数据',
          label: '请选择需要导出数据的年份',
          keyName: 'year',
          type: 'a-date-picker',
          attrs: {
            mode: 'year',
            format: 'YYYY',
            valueFormat: 'YYYY',
            disabledDate: (current) => {
              return true
            }
          },
          rules: {
            year: [{ required: true, message: '请选择', trigger: 'change' }]
          }
        }
      }
    }
  },

  watch: {
    dialogVisibleType(status) {
      if (status) {
        this.visible = true
        this.rules = this.dialogConifig[this.dialogVisibleType].rules
        this.handleFormInfo()
      } else {
        this.visible = false
        this.form = {}
      }
    },
    'form.year'() {
      this.$refs.ruleForm.clearValidate('year')
    }
  },

  components: {},

  computed: {
    currentShowConfig() {
      return this.dialogVisibleType ? this.dialogConifig[this.dialogVisibleType] : {}
    },
    formList() {
      return Object.keys(this.form)
    }
  },

  created() {},

  mounted() {},

  methods: {
    jointUrl(url, params) {
      let idx = url.indexOf('?')
      if (idx < 0) {
        url = url + '?'
      } else if (idx !== url.length - 1) {
        if (url.charAt(url.length - 1) !== '&') {
          url = url + '&'
        }
      }
      for (let key in params) {
        if (params.hasOwnProperty(key)) {
          let v = params[key]
          if (v !== '') {
            url += key + '=' + params[key] + '&'
          }
        }
      }
      console.log(url)
      return url
    },
    /**
     * 下载模板
     */
    downFile(year) {
      this.confirmLoading = true
      const link = document.createElement('a')
      const token = Vue.getAcloudProvider().getAccessToken()
      link.href = this.jointUrl(`/api${this.projectApiUrlList}/output/export-total?access_token=${token}`, {
        year
      })
      link.setAttribute('target', '_self')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      setTimeout(() => {
        this.confirmLoading = false
        this.handleCancel()
      }, 1000)
    },
    // 基础产值数据导出
    exportMonth() {
      // multiHeader数组里面添加的是一级表头的名称
      // 要按顺序添加每个表头的的名称，如果遇到横向合并单元格的地方，合并了多少个单元格，就要留几个空字符串占位
      const multiHeader = [
        ['5月度施工产值报表--西南分公司', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
      ]
      // tHeader数组里面放的是二级表头的名称，也要按顺序添加每个表头的的名称，
      // 添加的时候要注意，如果是一级表头上下单元格合并地方，要用空字符串补上占位。
      const tHeader = [
        '序号',
        '分局',
        '二级单位',
        '三级单位',
        '项目名称',
        '合同额（亿元）',
        '项目工期',
        '全年产值指标（万元）',
        '本月计划产值（万元）',
        '本月实际完成产值（万元）',
        '本月实际确认产值（万元）',
        '自年初累计完成确认产值（万元）',
        '自开工累计确认产值（亿元）',
        '月度计划完成率',
        '全口径人数（不含新生）',
        '新生人数',
        '产值完成率低于85%的项目填报',
        ''
      ]
      const threeHeader = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '主要原因（不超过3条）', '解决措施']
      // merges是进行所有表头的单元格合并，数组里面的每个元素的填写规则是：按从左往右的顺序依次填写，
      // 字母是指excel里面的第几列，数字表示第几行，如果是上下的单元格合并，就是按从上往下填写，比
      // 如'A1:A2'代表的是A列的第一个单元格和A列的第二个单元格合并，如果是左右的单元格合并，也是从左往右填写，同理，
      const merges = [
        'A1:P1',
        'A2:A3',
        'B2:B3',
        'C2:C3',
        'D2:D3',
        'E2:E3',
        'F2:F3',
        'G2:G3',
        'H2:H3',
        'I2:I3',
        'J2:J3',
        'K2:K3',
        'L2:L3',
        'M2:M3',
        'N2:N3',
        'O2:P2',
        'O3:O3',
        'P3:P3'
      ]

      const filterVal = [
        's1',
        's2',
        's3',
        's4',
        's5',
        's6',
        's7',
        's8',
        's9',
        's10',
        's11',
        's12',
        's13',
        's4',
        's15',
        's16'
      ]
      require.ensure([], () => {
        const { export_json_to_excel } = require('@/components/exportExcel/Export2Excel2')
        const list = [
          {
            s1: 1,
            s2: 1,
            s3: 1,
            s4: 1,
            s5: 1,
            s6: 1,
            s7: 1,
            s8: 1,
            s9: 1,
            s10: 1,
            s11: 1,
            s12: 1,
            s13: 1,
            s14: 1,
            s15: 1,
            s16: 1,
            s17: 1,
            s18: 1,
            s19: 1
          }
        ]
        const data = this.formatJson(filterVal, list) // 生成json数据
        export_json_to_excel({
          multiHeader2: [tHeader], // 这里是第一行的表头
          multiHeader: multiHeader, // 这里是第二行的表头
          header: [threeHeader],
          data,
          filename: 'xxxx', //这里填的是导出excel的名称
          merges
        })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]))
    },
    openChangeOne(status) {
      //status是打开或关闭的状态
      this.yearShowOne = !this.yearShowOne
    },
    handlePanelChange(val) {
      this.form[this.currentShowConfig.keyName] = val
      this.yearShowOne = !this.yearShowOne
    },
    handleFormInfo() {
      this.$set(this.form, this.currentShowConfig.keyName, undefined)
      return true
    },
    handleOk() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.dialogVisibleType === 'exportBaseVal') {
            this.confirmLoading = true
            const fileName = `${moment(this.form.month).get('year')}年${
              moment(this.form.month).get('month') + 1
            }月 月度施工产值报表（基础数据）`
            const pageSetup = {
              horizontalCentered: true,
              verticalCentered: true,
              defaultRowHeight: 20,
              defaultColWidth: 20,
              cellWidthCollections: [
                {
                  index: 2,
                  width: 20
                },
                {
                  index: 3,
                  width: 20
                },
                {
                  index: 4,
                  width: 20
                },
                {
                  index: 5,
                  width: 20
                },
                {
                  index: 6,
                  width: 20
                },
                {
                  index: 7,
                  width: 20
                },
                {
                  index: 8,
                  width: 20
                },
                {
                  index: 9,
                  width: 20
                },
                {
                  index: 10,
                  width: 20
                },
                {
                  index: 11,
                  width: 20
                },
                {
                  index: 12,
                  width: 20
                },
                {
                  index: 13,
                  width: 40
                },
                {
                  index: 14,
                  width: 40
                },
                {
                  index: 15,
                  width: 40
                },
                {
                  index: 16,
                  width: 20
                },
                {
                  index: 17,
                  width: 20
                },
                {
                  index: 18,
                  width: 20
                },
                {
                  index: 19,
                  width: 40
                },
                {
                  index: 20,
                  width: 40
                }
              ],
              appointRowHeight: [
                {
                  _number: 1,
                  height: 40
                },
                {
                  _number: 2,
                  height: 40
                },
                {
                  _number: 3,
                  height: 40
                }
              ]
            }
            const xlsxList = [
              {
                sheetName: '月度施工产值报表（基础数据）',
                titleObj: {
                  name: `${moment(this.form.month).get('month') + 1}月度施工产值报表--西南分公司`,
                  merge: 'A1:P1'
                },
                columns: [
                  {
                    name: '序号'
                  },
                  {
                    name: '分局'
                  },
                  {
                    name: '二级单位'
                  },
                  {
                    name: '三级单位'
                  },
                  {
                    name: '项目名称'
                  },
                  {
                    name: '签约合同额'
                  },
                  {
                    name: '自施合同额'
                  },
                  {
                    name: '开工时间'
                  },
                  {
                    name: '竣工日期'
                  },
                  {
                    name: '全年产值指标（万元）'
                  },
                  {
                    name: '本月计划产值（万元）'
                  },
                  {
                    name: '本月实际产值（万元）'
                  },
                  {
                    name: '本月确权产值（万元）'
                  },
                  {
                    name: '自年初累计完成产值（万元）',
                  },
                  {
                    name: '自开工累计产值（亿元）'
                  },
                  {
                    name: '完成率'
                  },
                  {
                    name: '全口径人数（不含新生）'
                  },
                  {
                    name: '新生人数'
                  },
                  {
                    name: '主要原因（不超过3条）'
                  },
                  {
                    name: '解决措施'
                  }
                ],
                rows: [],
                ref: 'A3',
                mergeOptions: [
                  {
                    merge: 'A2:A3'
                  },
                  {
                    merge: 'B2:B3'
                  },
                  {
                    merge: 'C2:C3'
                  },
                  {
                    merge: 'D2:D3'
                  },
                  {
                    merge: 'E2:E3'
                  },
                  // {
                  //   merge: 'F2:F3'
                  // },
                  // {
                  //   merge: 'G2:G3'
                  // },
                  {
                    merge: 'F2:G2',
                    value: '合同额（万元）'
                  },
                  {
                    merge: 'H2:I2',
                    value: '项目工期'
                  },
                  // {
                  //   merge: 'H2:H3'
                  // },
                  // {
                  //   merge: 'I2:I3'
                  // },
                  {
                    merge: 'J2:J3'
                  },
                  {
                    merge: 'K2:K3'
                  },
                  {
                    merge: 'L2:L3'
                  },
                  {
                    merge: 'M2:M3'
                  },
                  {
                    merge: 'N2:N3'
                  },
                  {
                    merge: 'O2:O3'
                  },
                  {
                    merge: 'P2:P3'
                  },
                  {
                    merge: 'Q2:Q3'
                  },
                  {
                    merge: 'R2:R3'
                  },
                  {
                    merge: 'S2:T2',
                    value: '产值完成率低于85%的项目填报'
                  }
                ]
              }
            ]
            // handleExcel(fileName, pageSetup, xlsxList)
            outputEexportBase({ monthly: moment(this.form.month).format('YYYY-MM') }).then((res) => {
              res.data.map((v, i) => {
                let arr = []
                const keys = [
                  'substation',
                  'implUnit2name',
                  'implUnit3name',
                  'projectName',
                  'contractAmount',
                  'selfContractAmount',
                  'startWorkingTime',
                  'completionTime',
                  'yearPlanOutput',
                  'planAmount',
                  'actAmount',
                  'confirmAmount',
                  'yearConfirmOutput',
                  'confirmTotalOutput',
                  'actualCompletionRate',
                  'employeeSize',
                  'traineesNumber',
                  'mainspring',
                  'countermeasure'
                ]
                arr.push(i + 1)
                keys.map((k) => {
                  arr.push(v[k])
                })
                xlsxList[0].rows.push(arr)
              })
              handleExcel(fileName, pageSetup, xlsxList)
                .then((res) => {
                  this.confirmLoading = false
                  this.handleCancel()
                })
                .catch(() => {
                  this.confirmLoading = false
                })
            }).catch(()=>{
              this.confirmLoading = false
            })
            // this.exportMonth()
          } else {
            this.downFile(moment(this.form.year).format('YYYY'))
          }
        }else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    handleCancel() {
      this.$refs.ruleForm.resetFields()
      this.visible = false
      this.$emit('update:dialogVisibleType', '')
    }
  }
}
</script>
<style lang='less' scoped>
@deep: ~'>>>';
@{deep}.ant-form-item .ant-form-item-label {
  width: 210px;
}
@{deep} .ant-form-item .ant-form-item-control-wrapper {
  width: 250px;
}
</style>
